/**
 * 
 * @param 
 * @param 
 * @return -1 监听失败 >0失败
 */
#define LISTEN_BACKLOG 1024
int tcp_listen(const char * host, const char * serv, socketlen_t *addrlenp)
{
    int listenfd=-1, n=0;
    const int on = 1;
    struct addrinfo hints, *res, *ressave;
    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    
    if(0!=(n=getaddrinfo(host, serv, &hints, &res))) {
        return listenfd;
    }
    ressave = res;

    do {
        listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if(listenfd<0) {
            continue;
        }

        setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
        if(0==bind(listenfd, res->ai_addr, res->ai_addrlen)) {
            break;
        }
        close(listenfd);
        listenfd = -1;
    }while(NULL!=(res=res->ai_next));

    if(listenfd>=0) {
        if(listen(listenfd, LISTEN_BACKLOG)<0) {
            close(listenfd);
            listenfd = -1;
        } else {
            if ( addrlenp ) {
                *addrlenp = res->ai_addrlen;
            }
        }
    }

    freeaddrinfo(ressave);
    return listenfd;
}
